package com.cfm880.latte.core.net.download;

import android.os.AsyncTask;

import com.cfm880.latte.core.net.RestCreator;
import com.cfm880.latte.core.net.callback.IError;
import com.cfm880.latte.core.net.callback.IFailure;
import com.cfm880.latte.core.net.callback.IRequest;
import com.cfm880.latte.core.net.callback.ISuccess;

import java.util.WeakHashMap;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by chengfangming on 2018/1/7.
 */

public class DownloadHandler {
    private static final WeakHashMap<String, Object> mParams = RestCreator.getParams();
    private final String mUrl;
    private final IRequest mRequest;
    private final String mDownloadDir;
    private final String mExtension;
    private final String mName;
    private final ISuccess mSuccess;
    private final IFailure mFailure;
    private final IError mError;

    public DownloadHandler(String url,
                           IRequest request,
                           String downloadDir,
                           String extension,
                           String name,
                           ISuccess success,
                           IFailure failure,
                           IError error) {
        this.mUrl = url;
        this.mRequest = request;
        this.mDownloadDir = downloadDir;
        this.mExtension = extension;
        this.mName = name;
        this.mSuccess = success;
        this.mFailure = failure;
        this.mError = error;
    }


    public final void handleDownload(){
        if (mRequest != null){
            mRequest.onRequestStart();
        }

        RestCreator.getRestService().download(mUrl, mParams)
            .enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response.isSuccessful()){
                        final SaveFileTask saveFileTask = new SaveFileTask(mRequest, mSuccess);
                        saveFileTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, mDownloadDir, mExtension, mName);
                        if (saveFileTask.isCancelled()){
                            if (mRequest != null){
                                mRequest.onRequestEnd();
                            }
                        }
                    } else {
                        if (mError != null){
                            mError.onError(response.code(), response.message());
                        }
                    }

                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    if (mFailure != null){
                        mFailure.onFailure();
                    }
                }
            });
    }
}
